local server = require "resty.websocket.server"
local redis  = require "resty.redis"

--push public quote info 
local push = function()
    -- --create redis
    local red = redis:new()
    red:set_timeout(5000) -- 1 sec
    local ok, err = red:connect("127.0.0.1", 6379)
    if not ok then
        ngx.log(ngx.ERR, "failed to connect redis: ", err)
        return
    end

    --sub
    local res, err = red:subscribe(channel_name)
    if not res then
        ngx.log(ngx.ERR, "failed to sub redis: ", err)
        return
    end

    local wb = nil;

    -- loop : read from redis
    while true do
        local res, err = red:read_reply()
        local continue = true; 

        if res then
            local item = res[3]
            local result = split(item,"|");
            local message = nil

            if not result then
                ngx.log(ngx.ERR, "data analysis error: ",item)
                continue = false
            end

            if result[1] == "0" then
                  message = result[2]
            elseif result[1] == "1" then
                 
                 wb = ngx.shared.session_info:get(result[2])

                 if wb.fatal then
                    ngx.log(ngx.ERR, "failed send message, because connection is broken,customerno=",customerno)
                    continue = false
                 else
                    message = result[3]
                 end
            end
            
            if continue then
                local bytes, err = wb:send_text(message)
                if not bytes then
                   -- better error handling
                   ngx.log(ngx.ERR, "failed to send text: ", err)
                end
            end
        end
    end
end

if not ngx.var.init then
   ngx.thread.spawn(push)
   ngx.var.init = true
end
